<template>
  <view class="hb-relative">
    <view class="hb-relative hb-w-full">
      <tm-input
        v-model="keyword"
        :placeholder="placeholder"
        :height="88"
        :font-size="28"
        @focus="handleFocus"
        @input="handleInput"
      >
        <template #right v-if="keyword || loading">
          <!-- <view @click.stop="clearInput" v-if="keyword && !loading">
            <text class="ali-icon icon-guanbi1 hb-text-gray-400 hb-text-lg"></text>
          </view> -->
          <view>
            <tm-spin :load="loading" :size="28" />
          </view>
        </template>
      </tm-input>
    </view>

    <!-- 点击遮罩层 -->
    <view
      v-if="showDropdown"
      class="hb-fixed hb-inset-0 hb-z-40"
      @click.stop="showDropdown = false"
    ></view>

    <!-- 搜索结果下拉框 -->
    <view
      v-show="showDropdown && searchResults.length > 0"
      class="hb-absolute hb-left-0 hb-right-0 hb-mt-1 hb-bg-white hb-border hb-border-solid hb-border-gray-200 hb-rounded hb-box-shadow-base hb-z-50"
      @click.stop
    >
      <scroll-view
        scroll-y
        class="hb-max-h-80"
        :scroll-top="scrollTop"
        @scrolltolower="loadMoreData"
      >
        <view
          v-for="(item, index) in searchResults"
          :key="index"
          class="hb-px-4 hb-py-3 hb-border-b hb-border-solid hb-border-gray-100 hb-cursor-pointer hover:hb-bg-gray-50"
          @click.stop="selectItem(item)"
        >
          <view class="hb-font-medium hb-text-sm">{{ item.name }}</view>
          <view class="hb-text-xs hb-text-gray-500 hb-mt-1">
            <text>{{ item.regStatus }}</text>
            <text class="hb-mx-2">|</text>
            <text>{{ item.base }}</text>
          </view>
        </view>

        <!-- 加载更多 -->
        <view v-if="hasMore" class="hb-py-2 hb-text-center hb-text-xs hb-text-gray-500">
          <text v-if="loadingMore" class="ali-icon icon-loading hb-mr-1 hb-animate-spin"></text>
          <text>{{ loadingMore ? '加载中...' : '向下滑动加载更多' }}</text>
        </view>

        <view v-else class="hb-py-2 hb-text-center hb-text-xs hb-text-gray-500">
          没有更多数据了
        </view>
      </scroll-view>
    </view>

    <!-- 无搜索结果提示 -->
    <view
      v-if="showDropdown && keyword && searchResults.length === 0 && !loading"
      class="hb-absolute hb-left-0 hb-right-0 hb-mt-1 hb-bg-white hb-border hb-border-solid hb-border-gray-200 hb-rounded hb-shadow-lg hb-z-50 hb-py-4 hb-text-center hb-text-gray-500 hb-text-sm"
      @click.stop
    >
      没有找到相关结果
    </view>
  </view>
</template>

<script lang="ts" setup>
  import { ref, computed, watch, onMounted, onUnmounted } from 'vue';
  import { tianyanchaDetail, tianyanchaSearch } from '@/api/card/index';
  import { TianyanchaResult } from '@/api/card/type';

  const props = defineProps({
    placeholder: {
      type: String,
      default: '请输入公司名称搜索，并选择',
    },
    name: {
      type: String,
      default: '',
    },
  });

  const emits = defineEmits(['select']);

  // 状态
  const keyword = ref('');
  const loading = ref(false);
  const loadingMore = ref(false);
  const showDropdown = ref(false);
  const searchResults = ref<TianyanchaResult[]>([]);
  const currentPage = ref(1);
  const pageSize = ref(10);
  const hasMore = ref(true);
  const timer = ref<any>(null);
  const scrollTop = ref(0);

  // 监听输入变化并防抖处理
  const handleInput = () => {
    loading.value = true;

    // 清除之前的定时器
    if (timer.value) {
      clearTimeout(timer.value);
    }

    // 设置新的定时器
    timer.value = setTimeout(() => {
      if (keyword.value) {
        searchData(true);
      } else {
        searchResults.value = [];
        showDropdown.value = false;
        loading.value = false;
      }
      emits('select', { name: keyword.value, id: undefined });
    }, 500);
  };

  // 搜索数据
  const searchData = async (isReset = false) => {
    if (isReset) {
      currentPage.value = 1;
      searchResults.value = [];
      hasMore.value = true;
      scrollTop.value = 0; // 重置滚动位置
    }

    try {
      loading.value = true;

      if (isReset) {
        loadingMore.value = false;
      } else {
        loadingMore.value = true;
      }

      const params = {
        keyword: keyword.value,
        pageNum: currentPage.value,
        pageSize: pageSize.value,
      };

      const res = await tianyanchaSearch(params);

      const dataList = res.records || [];

      if (isReset) {
        searchResults.value = dataList;
      } else {
        searchResults.value = [...searchResults.value, ...dataList];
      }

      // 判断是否还有更多数据
      if (dataList.length < pageSize.value) {
        hasMore.value = false;
      } else {
        hasMore.value = true;
      }
    } catch (error) {
      console.error('搜索失败', error);
    } finally {
      loading.value = false;
      loadingMore.value = false;
      showDropdown.value = true;
    }
  };

  // 滚动到底部时加载更多
  const loadMoreData = () => {
    if (hasMore.value && !loadingMore.value) {
      currentPage.value++;
      searchData(false);
    }
  };

  // 选择项目
  const selectItem = async (item: TianyanchaResult) => {
    nextTick(() => {
      emits('select', item);
      showDropdown.value = false;
      keyword.value = item.name;
    });
  };

  // 聚焦时显示下拉框
  const handleFocus = () => {
    showDropdown.value = true;

    if (keyword.value && searchResults.value.length === 0) {
      searchData(true);
    }
  };

  watch(
    () => props.name,
    (newVal) => {
      keyword.value = newVal;
    },
  );

  onUnmounted(() => {
    if (timer.value) {
      clearTimeout(timer.value);
    }
  });
</script>

<style lang="scss" scoped>
  /* 使用WindiCSS，无需额外样式 */
</style>
